<template>
  <n-grid cols="1" responsive="screen" class="-mt-5">
    <n-grid-item>
      <n-list>
        <n-list-item>
          <template #suffix>
            <n-button type="primary" text @click="clickModify">修改</n-button>
          </template>
          <n-thing title="账户密码">
            <template #description
            ><span class="text-gray-400">设置密码，帐号更安全</span></template
            >
          </n-thing>
        </n-list-item>
      </n-list>
    </n-grid-item>
  </n-grid>
  <n-modal v-model:show="modifyPasswd" :show-icon="false" preset="dialog" title="修改密码">
    <n-form
      :model="formParams"
      :rules="rules"
      ref="formRef"
      label-placement="left"
      :label-width="100"
      class="py-4"
    >
      <n-form-item label="原密码" path="oldPassword">
        <n-input placeholder="请输入原始密码" v-model:value="formParams.oldPsw"/>
      </n-form-item>
      <n-form-item label="新密码" path="password">
        <n-input placeholder="新密码" type="password" v-model:value="formParams.newPsw"/>
      </n-form-item>
      <n-form-item label="确认密码" path="rePassword">
        <n-input placeholder="确认密码" type="password" v-model:value="formParams.rePassword"/>
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button type="info" ghost icon-placement="left" @click="cancelDialog">
          取消
        </n-button>
        <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">提交</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>

  import {reactive, ref, unref} from "vue";
  import {FormItemRule, useMessage} from "naive-ui";
  import {useUserStore} from "@/store/modules/user";
  import {changePassword} from "@/api/system/user";

  const rules = {
    rePassword: [{required: true, message: '再次输入密码', trigger: ['blur']}, {
      validator: validatorPassword,
      message: '两次密码输入不一致',
      trigger: ['blur', 'password-input']
    }]
  };

  const userStore = useUserStore();
  const modifyPasswd = ref(false);
  const message = useMessage();
  const formBtnLoading = ref(false);

  const formParams = reactive({
      newPsw: "",
      oldPsw: "",
      rePassword: "",
      userId: 0
    })
  ;

  async function confirmForm() {
    formBtnLoading.value = true;
    let userId = unref(userStore.getUser).id;
    let params = Object.assign({}, formParams, {userId});
    delete params.rePassword;
    try {
      await changePassword(params);
      message.success("修改成功，下次登陆生效")
      cancelDialog()
    } finally {
      formBtnLoading.value = false;
    }
  }

  function cancelDialog() {
    modifyPasswd.value = false
  }

  function validatorPassword(rule: FormItemRule, value: string) {
    return value === unref(formParams).newPsw
  }

  function clickModify() {
    modifyPasswd.value = true
  }


</script>
